import type { Ref } from 'vue'

/**
 * 数字动画
 * @param refValue 目标值
 * @param target 最终值
 * @param duration 动画持续时间，单位毫秒
 */
export function animateToNumber(refValue: Ref<number>, target: number, duration: number = 1000) {
  const start = refValue.value
  const startTime = Date.now()
  const interval = 16 // 约60fps
  let timeoutId: number

  const update = () => {
    const elapsed = Date.now() - startTime
    const progress = Math.min(elapsed / duration, 1) // 计算进度
    refValue.value = Math.round(start + (target - start) * progress)

    if (progress < 1) {
      timeoutId = setTimeout(update, interval)
    } else {
      refValue.value = target // 确保最终值准确
      clearTimeout(timeoutId) // 清理定时器
    }
  }

  update()
}
